<?php

declare(strict_types=1);

namespace Zms\Validate\Traits;

use Zms\Exception\ValidateException;
use Zms\Unit\Is;

trait ValidateTraits
{

    /**
     * @return mixed
     * @throws ValidateException
     * @example 比较两个字段的数据是否一致
     * @attr   'value' => '比对的值','find' => '要比较的字段','data' => '请求数据', 'rule' => '验证规则'
     */
    protected function compareValidate($value, string $find, array $data, array $rule)
    {
        if (isset($rule['find']) && $rule['find']) {
            if ($value === ($data[$rule['find']] ?? '')) {
                return $value;
            } else {
                $this->addError($find, $rule['error'] ?? "{label}和" . ($this->_labels[$rule['find']] ?? $rule['find']) . "不一致");
            }
            return null;
        } else {
            throw new ValidateException('请配置compare规则的key');
        }
    }


    /**
     * @return mixed
     * @example 给没有值的内容设置默认值
     * @attr   'value' => '比对的值','find' => '要比较的字段','data' => '请求数据', 'rule' => '验证规则'
     */
    protected function defaultValidate($value, string $find, array $data, array $rule)
    {
        if (Is::empty($value)) {
            return $rule['value'];
        }
        $safe = $this->getSafe($find);
        if (is_null($safe)) {
            return $value;
        }
        return $safe;
    }
}